package com.pz.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.pz.gulimall.common.exception.BizCodeEnum;
import com.pz.gulimall.common.utils.R;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;

import javax.annotation.PostConstruct;

@Configuration
public class SentinelConfig {
    /**
     * 自定义Sentinel异常
     */
    @PostConstruct
    private void initBlockHandler(){

        BlockRequestHandler blockRequestHandler = (serverWebExchange, throwable) -> {
            R error = R.error(BizCodeEnum.TOO_MANY_REQUEST);

            return ServerResponse.status(error.getCode())
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(BodyInserters.fromValue(error));
        };
        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    }
}
